package edu.zut.controller;

import edu.zut.dao.UserDao;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //编码的设定
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取表单提交数据
        String user_name = request.getParameter("user_name");
        String user_psw = request.getParameter("user_psw");
        System.out.println("user_name = " + user_name);
        System.out.println("user_psw = " + user_psw);
        String error;
        //验证用户名和密码是否为空，如果为空，返回登录页面，并告知用户用户名或密码不能为空
        if (null == user_name || user_name.trim().length() == 0
                || null == user_psw || user_psw.trim().length() == 0) {
            error = "用户名或密码不能为空";
            //转发到登录页面资源,同时需要携带动态的提示信息
            request.setAttribute("error", error);
            //获取一个转发器，指定要转发的资源路劲,转发是我们服务器内部资源的跳转，他们是共享request和response的
            RequestDispatcher dispatcher = request.getRequestDispatcher("/loginPage");
            dispatcher.forward(request, response);
        } else {
            //如果用户名、密码不为空,调用数据层中的操作验证
            UserDao userDao = new UserDao();
            boolean result = userDao.userLogin(user_name, user_psw);
            if (result) {
                //用户名和密码匹配后，登录成功，跳转到首页
                request.setAttribute("name",user_name);
                request.getRequestDispatcher("/indexPage").forward(request,response);
            } else {
                //用户名或密码不匹配
                error = "用户名或密码错误";
                request.setAttribute("error", error);
                request.getRequestDispatcher("/loginPage").forward(request, response);
            }
        }


    }
}
